use rustls::pki_types::ServerName;
use std::fs::File;
use std::io::BufReader;
use std::net::{Ipv4Addr, SocketAddrV4};
use std::path::Path;
use std::sync::Arc;
use tarpc::client::Config;
use tarpc::context::Context;
use tarpc::tokio_serde::formats::Bincode;
use tokio::net::TcpStream;
use tokio_rustls::TlsConnector;

#[tarpc::service]
trait HelloService {
    async fn hello(string: String);
}

#[allow(dead_code)]
async fn connect() -> HelloServiceClient {
    let mut root_cert_store = rustls::RootCertStore::empty();

    let mut pem = BufReader::new(File::open(Path::new("ca-cert.pem")).unwrap());
    for cert in rustls_pemfile::certs(&mut pem) {
        root_cert_store.add(cert.unwrap()).unwrap();
    }

    let config = rustls::ClientConfig::builder()
        .with_root_certificates(root_cert_store)
        .with_no_client_auth();
    let connector = TlsConnector::from(Arc::new(config));

    let stream = TcpStream::connect(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 1234))
        .await
        .unwrap();
    let mut transport = tarpc_rustls::tls::connect(
        connector,
        stream,
        ServerName::DnsName("network-scanner-server".try_into().unwrap()),
        Bincode::default,
    );
    transport.config_mut().max_frame_length(1024usize);

    let transport = transport.await.unwrap();

    HelloServiceClient::new(Config::default(), transport).spawn()
}

#[tokio::main]
async fn main() {
    let client = connect().await;
    println!("Connected");
    client
        .hello(Context::current(), "Hello, world!".to_string())
        .await
        .unwrap();
}
